package com.example.servlet;


import com.example.dao.UserDao;
import com.example.dao.imp.UserDaoImp;
import com.example.domain.Users;
import com.example.utils.ResponseUtil;
import org.apache.commons.lang3.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "AutoLoginServlet", value = "/autoLogin")
public class AutoLoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String rememberMeToken = request.getParameter("rememberMeToken");

        if (rememberMeToken != null && !rememberMeToken.isEmpty()) {
            UserDao userDao = new UserDaoImp();
            // 根据Token查询用户信息
            Users user = userDao.getUsersByUserId(Integer.valueOf(rememberMeToken));
            if (ObjectUtils.isNotEmpty(user)) {
                // 用户信息存入session，用于登录后的其它请求校验使用，避免被authFilter过滤器拦截。
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                ResponseUtil.sendSuccessResponse(response, 200, user.getRole());
            }
        }
    }
}
